package cn.edu.zstu.qingzhu.qingzhushop.handler;

import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-03-08 20:04
 */
@Component
public class CustomAuthenticationAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        ResponseBean retTemp = new ResponseBean.Builder()
                .setStatus(401)
                .setMsg("权限不足")
                .build();
        out.write(new ObjectMapper().writeValueAsString(retTemp));
        out.flush();
        out.close();
    }
}
